package cn.org.processor.guestbook.admin.service.impl;

import cn.org.processor.guestbook.admin.mapper.TopicMapper;
import cn.org.processor.guestbook.admin.model.response.PageResponse;
import cn.org.processor.guestbook.admin.service.TopicService;
import entity.Topic;
import io.Page;
import io.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import util.PageUtil;

import java.util.List;

@Service
@Slf4j
public class TopicServiceImpl implements TopicService {
    private final TopicMapper topicMapper;

    public TopicServiceImpl(TopicMapper topicMapper) {
        this.topicMapper = topicMapper;
    }

    @Override
    public Response list(Page page) {
        int count = topicMapper.getCount();

        int start = PageUtil.getStartRows(page);
        List<Topic> topics = topicMapper.list(start, page.getOffset());
        topics.forEach(topic -> {
            if (topic.getContent().length() > 100) {
                topic.setContent(topic.getContent().substring(0, 100) + "...");
            }
        });

        PageResponse response = new PageResponse();
        response.setTotal(count);
        response.setList(topics);

        return Response.builder().ret(Response.Ret.SUCCESS).msg("获取成功").data(response).build();
    }

    @Override
    public Response lock(Integer id) {
        Topic topic = topicMapper.findById(id);
        if (topic == null) {
            return Response.builder().ret(Response.Ret.FAILURE).msg("话题不存在").build();
        }

        Topic update = new Topic();
        update.setId(id);
        update.setStatus(Topic.Status.CLOSE);
        if (topicMapper.update(update) > 0) {
            return Response.builder().ret(Response.Ret.SUCCESS).msg("操作成功").build();
        }

        log.error("Fail to lock topic {}", topic);
        return Response.builder().ret(Response.Ret.FAILURE).msg("操作失败").build();
    }

    @Override
    public Response unlock(Integer id) {
        Topic topic = topicMapper.findById(id);
        if (topic == null) {
            return Response.builder().ret(Response.Ret.FAILURE).msg("话题不存在").build();
        }

        Topic update = new Topic();
        update.setId(id);
        update.setStatus(Topic.Status.OPEN);
        if (topicMapper.update(update) > 0) {
            return Response.builder().ret(Response.Ret.SUCCESS).msg("操作成功").build();
        }

        log.error("Fail to lock topic {}", topic);
        return Response.builder().ret(Response.Ret.FAILURE).msg("操作失败").build();
    }

    @Override
    public Response detail(Integer id) {
        Topic topic = topicMapper.findById(id);
        if (topic == null) {
            return Response.builder().ret(Response.Ret.FAILURE).msg("话题不存在").build();
        }

        return Response.builder().ret(Response.Ret.SUCCESS).msg("获取成功").data(topic).build();
    }
}
